package com.cgtong.android.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.event.LoadUserInfoEvent;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.LoginContract;
import com.cgtong.android.mvp.presenter.LoginPresenter;
import com.cgtong.android.util.MD5Utils;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.ValidCodeTime;
import com.kingja.loadsir.callback.SuccessCallback;
import com.umeng.analytics.MobclickAgent;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.IProgressDialog;
import com.cgtong.android.util.CommonUtils;

import org.simple.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Sky.Bing on 2017/10/20.
 */

public class LoginActivity extends BaseTitleActivity implements LoginContract.View {
    public static final String EXTRA_USER_TOKEN = "user_token";
    //采用startActivity调用时，可指定登录成功之后跳转的页面
    public static final String EXTRA_LOGINED_SHOW_PAGE = "show_page";
    @BindView(R.id.et_login_phone)
    public EditText mEtPhone;
    @BindView(R.id.et_login_password)
    public EditText mEtPassword;

    @BindView(R.id.et_validcode)
    public EditText mEtValidCode;
    @BindView(R.id.btn_getvalidcode)
    public Button mBtnGetValidCode;
    @BindView(R.id.tv_validcode_login)
    public TextView mTvValidCodeLogin;
    @BindView(R.id.password_line)
    public View mPasswordLine;
    @BindView(R.id.validcode_layout)
    public RelativeLayout mValidCodeLayout;
    @BindView(R.id.validcode_line)
    public View mValidCodeLine;

    private int mLoginType = 1; //1:密码登录 2：验证码登录
    private int mPrevoiusPageIndex;
    private LoginContract.Presenter mLoginPresenter;

    private ValidCodeTime timeCount;

    @Override
    protected String getContentTitle() {
        return getResources().getString(R.string.txt_title_login);
    }

    @Override
    protected void loadDataByNet() {
//        mEtPhone.setText("13852146640");
//        mEtPassword.setText("111111");
        timeCount = new ValidCodeTime(60000, 1000);
        timeCount.setTimeSetBtn(mBtnGetValidCode);
        mTitleCenterTxt.setVisibility(View.GONE);
        mTitleRightTxt.setVisibility(View.VISIBLE);
        mTitleRightTxt.setText(getResources().getString(R.string.txt_btn_register));
        mTitleRightTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                LoginActivity.this.startActivity(intent);
            }
        });
        mLoginPresenter = new LoginPresenter(this);
        Intent intent = getIntent();
        if (null != intent) {
            mPrevoiusPageIndex = intent.getIntExtra(LoginActivity.EXTRA_LOGINED_SHOW_PAGE, 0);
        }
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
    }

    @Override
    protected void onDataReloadByNet(View v) {
    }

    @Override
    public void breakClickValidCode() {
        timeCount.start();
        ToastUtils.showLong(R.string.txt_success_send_valid_code);
    }

    @OnClick(R.id.tv_forget_password)
    public void goForgetPasswordPage() {
        Intent intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
        LoginActivity.this.startActivity(intent);
    }

    @Override
    protected void backClick() {
        if (mPrevoiusPageIndex == ConstantManager.MAIN_PAGE_INDEX) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        } else {
            setResult(RESULT_CANCELED);
        }
        super.backClick();
    }

    @Override
    public void onBackPressed() { //点击back键触发
        backClick();
        super.onBackPressed();
    }

    @Override
    public void backActivity(String token) {
        if (mPrevoiusPageIndex == ConstantManager.MAIN_PAGE_INDEX) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            Intent intent = getIntent();
            intent.putExtra(EXTRA_USER_TOKEN, token);
            setResult(RESULT_OK, intent);
            EventBus.getDefault().post(new LoadUserInfoEvent());
            finish();
        }
    }

    @OnClick(R.id.btn_login)
    public void doLogin() {
        String phone = mEtPhone.getText().toString();
        String password = mEtPassword.getText().toString();
        String validCode = mEtValidCode.getText().toString();
        String passwordParam = "";

        if (mLoginType == 1) {
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showLong(R.string.txt_empty_phone);
                return;
            }
            if (!RegexUtils.isMobileSimple(phone)) {
                ToastUtils.showLong(R.string.txt_phone_format_error);
                return;
            }
            if (TextUtils.isEmpty(password)) {
                ToastUtils.showLong(R.string.txt_empty_password);
                return;
            }
            passwordParam = MD5Utils.md5(password);
            mLoginPresenter.doLogin(phone, passwordParam,CommonUtils.getMobileInfo(this), new IProgressDialog() {
                @Override
                public Dialog getDialog() {
                    ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
                    dialog.setMessage("登录中...");
                    return dialog;
                }
            });
        } else {
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showLong(R.string.txt_empty_phone);
                return;
            }
            if (!RegexUtils.isMobileSimple(phone)) {
                ToastUtils.showLong(R.string.txt_phone_format_error);
                return;
            }
            if (TextUtils.isEmpty(validCode)) {
                ToastUtils.showLong(R.string.txt_empty_validcode);
                return;
            }
            mLoginPresenter.doLogin(phone, passwordParam,CommonUtils.getMobileInfo(this), validCode, new IProgressDialog() {
                @Override
                public Dialog getDialog() {
                    ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
                    dialog.setMessage("登录中...");
                    return dialog;
                }
            });
        }
    }

    @OnClick(R.id.tv_validcode_login)
    public void showValidCodeLogin() {
        if (mLoginType == 1) {  //->验证码登录
            mLoginType = 2;
            mEtPassword.setText("");
            mEtValidCode.setText("");
            mTvValidCodeLogin.setText(R.string.txt_password_login);
            mValidCodeLayout.setVisibility(View.VISIBLE);
            mValidCodeLine.setVisibility(View.VISIBLE);
            mEtPassword.setVisibility(View.GONE);
            mPasswordLine.setVisibility(View.GONE);
        } else {  //->密码登录
            mLoginType = 1;
            mEtPassword.setText("");
            mEtValidCode.setText("");
            mTvValidCodeLogin.setText(R.string.txt_validcode_login);
            mEtPassword.setVisibility(View.VISIBLE);
            mPasswordLine.setVisibility(View.VISIBLE);
            mValidCodeLayout.setVisibility(View.GONE);
            mValidCodeLine.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.btn_getvalidcode)
    public void getValidCode() {
        String phone = mEtPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showLong(R.string.txt_empty_phone);
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showLong(R.string.txt_phone_format_error);
            return;
        }
        mLoginPresenter.sendValidCode(phone);
    }

    @Override
    public void sendValidCodeError(ApiException e) {
        //验证：用户不存在，去注册
        if (e.getCode() == -8) { //用户不存在，去注册
            ToastUtils.showShort(R.string.txt_user_no_exists);
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            intent.putExtra(RegisterActivity.EXTRA_REGISTERED_SHOW_PAGE, mPrevoiusPageIndex);
            LoginActivity.this.startActivity(intent);
            finish();
        } else {
            if (!TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.showLong(e.getMessage());
            } else {
                ToastUtils.showLong(R.string.txt_sendvalidcode_error);
            }
        }
    }

    @Override
    public void onLoginError(ApiException e) {
        if (e.getCode() == ConstantManager.CODE_USER_NO_EXISTS) { //用户不存在，去注册
            ToastUtils.showShort(R.string.txt_user_no_exists);
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            intent.putExtra(RegisterActivity.EXTRA_REGISTERED_SHOW_PAGE, mPrevoiusPageIndex);
            LoginActivity.this.startActivity(intent);
            finish();
        } else {
            if (TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.showLong(R.string.txt_error_login);
            } else {
                ToastUtils.showLong(e.getMessage());
            }
        }
    }

    public int getLayoutId() {
        return R.layout.activity_login;
    }
}